//index.js
//获取应用实例
const app = getApp()
Page({
  data: {
    wordContent: '',
    dkheight: 50,
    br: '\n',
    articleList: [],
    aList: [],
    activeNames: 1,
    kk: 1,
    info: '',
    module: 3,
    currentPage: 1,
    aPage: 1,
    flag: false,
    hotContent: {},
    dkcontent: "",
    dkcontent2: "",

  },
  imgExists: function(e) {

    //默认图片  
    var imgUrl = "2.jpg";
    var img = event.srcElement;
    img.src = imgUrl;
    console.log(img);
    //判断图片大小是否大于0 或者 图片高度与宽度都大于0
    if (img.filesize > 0 || (img.width > 0 && img.height > 0)) {
      e.src = imgUrl;
    } else {
      //默认图片也不存在的时候
    }
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  moveToLocation() {
    wx.navigateTo({
      url: '/pages/index/index',
    })
  },
  strSolver(item) {
    let reg = /[\u4e00-\u9fa5]/g;
    let strs = item.content.replace("\"", "").trim().match(reg);
    console.log("strs", strs)
    if (strs != null && strs.length > 0) {
      let str = strs.join("");
      item.content = str.trim().replace("宋体", "【点击查看详情】")
    } else {
      item.content = "【点击查看详情】"
    }
    return item
  },
  getArticle(page, key) {
    wx.showLoading({
      title: '加载中...',
    })
    let serverUrl = app.serverUrl
    let _this = this
    let url = `${serverUrl}/article/page?moduleId=${key}&current=${page}&size=10`
    // let url = `http://localhost:888/article/page?moduleId=1&current=${page}&size=10`
    wx.request({
      header: app.globalData.header,
      url: url,
      method: "GET",
      success: function(res) {
        console.log("article", res)
        if (res.data.code == 0) {
          wx.hideLoading()
          wx.hideNavigationBarLoading()
          wx.stopPullDownRefresh()
          let data = res.data.content.records
          let articleList = data;
          let newArticleList = _this.data.articleList;
          let _articleList = newArticleList.concat(articleList)
          for (let item of _articleList) {
            _this.strSolver(item)
          }
          console.log('_articleList', _articleList)
          _this.setData({
            articleList: _articleList,
            currentPage: page,
            totalPage: Math.floor((res.data.content.total / 10)) + 1,
          })
          console.log(_this.data.articleList)

        } else {
          wx.showToast({
            title: '网络出问题了哦..',
            icon: 'none'
          })
        }

      }
    })
  },
  onReachBottom: function(e) {
    let _this = this;
    let currentPage = _this.data.currentPage;
    let totalPage = _this.data.totalPage;
    console.log(currentPage, totalPage)
    //判断当前页数和总页数是否相等，如果相等则无需查询
    if (currentPage === totalPage) {
      wx.showToast({
        title: '已经是全部啦~~~',
        icon: 'none'
      })
      return;
    }
    let page = currentPage + 1;
    if (_this.data.search != undefined && _this.data.search != '') {
      this.onSearch(e, -1, page);
    } else {
      this.getArticle(page, _this.data.module);
    }


  },
  onPullDownRefresh: function() {
    let _this = this
    wx.showNavigationBarLoading();
    this.setData({
      articleList: [],
      currentPage: 1,
      search: '',
      searchValue: ''
    })
    this.getArticle(1, _this.data.module);
  },
  wxLogin() {

    let _this = this
    wx.login({
      success(res) {
        _this.setData({
          id: res.code
        })
        console.error('res.code', res.code)
        wx.getSetting({
          success: function(ret) {

            wx.getUserInfo({
              lang: "zh_CN",
              withCredentials: true,
              success: function(info) {
                console.log('res', info)
                let s = JSON.parse(info.rawData)
                console.error('s.avatarUrl', s.avatarUrl, s.nickName)
                console.error(s.avatarUrl == '')
                if (s.nickName != null && s.avatarUrl != null) {
                  let avatar = s.avatarUrl
                  avatar = s.avatarUrl == '' ? 'http://zzuisa.cn/unlogin.png' : s.avatarUrl
                  wx.request({
                    url: app.serverUrl + `/user/member/wxlogin`,
                    method: 'post',
                    data: {
                      code: res.code,
                      name: s.nickName,
                      headerImg: avatar,
                      gender: s.gender,
                      province: s.province,
                      city: s.city
                    },
                    success: function(reso) {
                      console.log('resooo', reso)
                      if (reso.data.code == 0) {
                        wx.hideLoading()
                        _this.setData({
                          userInfo: reso.data.content
                        })
                        app.setGlobalUserInfo(reso.data.content)
                        app.globalData.header.Cookie = reso.header["Set-Cookie"];
                        wx.hideLoading()
                        if (_this.data.page != undefined) {
                          let page = _this.data.page
                          wx.navigateTo({
                            url: decodeURIComponent(page.replace('article@', 'article?').replace('video@', 'video?'))
                          })
                        }
                      }

                    }
                  })
                }

              }
            })
          }
        })
      }
    })
  },
  toArticle(e) {
    console.log("ee", e)
    let _this = this
    let entity = this.data.articleList[e.target.dataset.arrindex]
    let _id = entity.id
    entity.title = entity.title.replace("[", "(").replace("]", ")")
    if (entity.module_id == 6) {
      wx.navigateTo({
        url: `../article/article?id=${_id}&type=trans&title=${entity.title}`,
      })
    } else {
      wx.navigateTo({
        url: `../article/article?id=${_id}&type=ex&title=${entity.title}`,
      })
    }

  },
  onLoad: function(param) {
    // 获得高度
    console.log('param', param)
    let winPage = this;
    wx.getSystemInfo({
      success: function(res) {
        let winHeight = res.windowHeight;
        console.log(winHeight);
        winPage.setData({
          dkheight: winHeight - winHeight * 0.05 - 80
        })
      }
    })
    if (param.word != undefined) {
      console.log('ee', param.word)
      this.setData({
        info: param.word,
        value: param.word
      })
      this.onSearch()
    }
    this.getArticle(1, this.data.module)
  },
  onSearch(e, key, page, kk) {
    let _this = this
    console.log(key, page)
    let title = _this.data.info
    if (title == undefined || title == '') {
      wx.showToast({
        title: '请输入关键词',
        icon: 'none'
      })
      return false
    }
    page = page == undefined ? 1 : page
    let serverUrl = app.serverUrl
    if (key != -1) {
      _this.setData({
        articleList: [],
      })
    }
    let url = `${serverUrl}/article/page?title=${title}&current=${page}&size=10&moduleId=${_this.data.module}`
    // let url = `http://localhost:888/article/page?title=${this.data.search}&current=${page}&size=10`
    wx.request({
      header: app.globalData.header,
      url: url,
      method: "GET",
      success: function(res) {
        console.log("articleee", res)
        if (res.data.code == 0) {
          wx.hideLoading()
          wx.hideNavigationBarLoading()
          let data = res.data.content.records
          // _this.setData({
          //   articleList: []
          // })
          let articleList = data;
          let newArticleList = _this.data.articleList;

          let _articleList = newArticleList.concat(articleList)
          for (let item of _articleList) {
            item.content = item.content.replace('<div>', '').replace('<p>', '').replace('</div>', '').replace('</p>', '')
          }
          console.log('_articleList', _articleList)
          _this.setData({
            articleList: _articleList,
            currentPage: page,
            totalPage: Math.floor((res.data.content.total / 10)) + 1,
          })
          console.log(_this.data.articleList)
        } else {
          _this.wxLogin()
          wx.showToast({
            title: '网络错误,请重试',
            icon: 'none'
          })

        }

      }
    })
  },
  onChange(e) {
    this.setData({
      info: e.detail
    })
  },
  change(event) {
    this.setData({
      activeNames: event.detail,
      kk: event.detail.index,
      module: event.detail.index + 3,
      articleList: [],
    });
    console.log('ree', event)
    this.getArticle(1, this.data.module)
  },
  onShareAppMessage() {},

})